package com.yitong.base.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.yitong.base.domain.JsonResponse;
import com.yitong.base.domain.Page;
import com.yitong.base.email.MyAuthenticator;

/**
 * @author 邓杰
 * @date 2015/10/22
 */
@Controller
public class BaseController {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;

	protected Page<?> page;

	private Gson gson = new Gson();

	@ModelAttribute
	public void setReqAndResp(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		this.session = request.getSession(true);
	}

	/**
	 * 获取参数列表
	 * 
	 * @return map
	 */
	protected Map<String, Object> getParameters() {
		Map<String, String[]> req = request.getParameterMap();
		if ((req != null) && (!req.isEmpty())) {
			Map<String, Object> p = new HashMap<String, Object>();
			Collection<?> keys = req.keySet();
			for (Iterator<?> i = keys.iterator(); i.hasNext();) {
				String key =  i.next().toString();
				Object value = req.get(key);
				Object v = null;
				if ((value.getClass().isArray()) && (((Object[]) value).length == 1)) {
					v = ((Object[]) value)[0];
				} else {
					v = value;
				}
				if ((v != null) && ((v instanceof String))) {
					String s = ((String) v).trim();
					if (s.length() > 0) {
						p.put(key, s);
					}
				}
			}
			return p;
		}
		return null;
	}

	/**
	 * 设置参数
	 * 
	 * @param map
	 */
	public void setParameters(Map<String, Object> map) {
		if (map != null) {
			Iterator<?> it = map.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				Object value = map.get(key);
				this.request.setAttribute(key, value);
			}
		}
	}

	/**
	 * DWZ的跳转方法，将数据转换为JSON对象
	 * 
	 * @param obj
	 */
	public void forDwzResult(Object obj) {
		try {
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.print(gson.toJson(obj));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 检查用户是否登录
	 * @return
	 */
	public boolean checkTabUserLogin(){
		//TabUser user = (TabUser) session.getAttribute(Constant.USER_SESSION);
		return true;
		/*		if(user!=null){
			return true;
		}else{
			return false;
		}*/
	}
	
	
	 /** 基于@ExceptionHandler异常处理 
     * @throws IOException */  
    @ExceptionHandler(Exception.class) 
    @ResponseBody
    public void exp(HttpServletRequest request, Exception ex,HttpServletResponse response) throws Exception {  
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=UTF-8");
    	JsonResponse jsonerror =new JsonResponse();
		String param=request.getParameter("param");
		jsonerror.setMessage("处理错误,请反馈"+ex.getMessage());
		jsonerror.setSuccess(false);
        logger.error("url"+request.getRequestURL().toString()+"param"+param);
        try{
        	MyAuthenticator.sendEmaiil("url"+request.getRequestURL().toString(),"param"+param+"异常"+ex.getMessage());	
        }catch(Exception e){
        	
        }
		PrintWriter out = response.getWriter();
		out.print(JSONObject.toJSONString(jsonerror));
		out.flush();
		out.close();
		ex.printStackTrace();
    }  
	
	

	public Page<?> getPage() {
		return page;
	}

	public void setPage(Page<?> page) {
		this.page = page;
	}

}